from version import version
import sys, os
import pysvn
from mbcc import ConfigClass
import re
import ConfigParser        

class mbbs_projdirconfigentry:
    def __init__(self, name):
        self.projectname = name
        self.projectdir = ""
        
class mbbs_projdirconfig:
    def __init__(self, filename):
        self.__filename__= filename
        self.projects = {}
        
        if os.path.isfile(self.__filename__):
            self.load()
        else:
            self.save()
        
    def addProject(self, prj):
        self.projects[prj.projectname] = prj
        self.save()
    
    def load(self):
        config = ConfigParser.ConfigParser()
        config.read(self.__filename__)
        self.projects = {}
        for sec in config.sections():
            mprj = mbbs_projdirconfigentry(sec)
            for option in config.options(sec):
                mprj.__dict__[option] = config.get(sec,option)

            self.projects[sec]=mprj
           
    def save(self):
        config = ConfigParser.ConfigParser()
        for q in self.projects.keys():
            prj = self.projects[q]
            config.add_section(q)
            for i in prj.__dict__.keys():
                if i != "projectname":
                    key = i
                    value = prj.__dict__[i]
                    config.set(q,key,value)
                
            
        fd = open(self.__filename__,"w")
        config.write(fd)
        fd.close()

            
        
class mbbs_userconfig(ConfigClass):
    def __init__(self, filename):

        self.rpmbuilddir = "~/rpmbuild"
        self.packagername = "Marco Bartel"
        self.packageremail = "mab@iee.lu"
        self.editor = "joe"
        
        self.__filename__ = filename
        
        if os.path.isfile(self.__filename__):
            self.load()
        else:
            self.save()
            
class mbbs_api:
    def __init__(self):
      self.vars = {}
      self.projects = {}
    
    def mbbs_cd(self, param=""):
      cmd, param=self.divideCmdString(param)
      if cmd=="..":
          print ".."
          os.chdir(os.pardir)
      elif cmd=="/":
          print "/"
          os.chdir(os.path.join("","/"))
      else:
          print cmd
          newpath = os.path.join(os.getcwd(), cmd)
          try:
              os.chdir(newpath)
          except:
              return("ERROR: No such directory")
      
    def mbbs_exit(self):
      sys.exit(0)        
  
    def startup(self, param=""):
          platform = sys.platform
          self.execute("setvar PLATFORM %s" % platform)
          if platform=="linux2":
              
              mbbsuserdir = os.path.join(self.replaceVars("%{HOME}"), "mbbs")
              self.execute("setvar MBBSMAINCONFIGDIR /etc/sysconfig/mbbs")
              self.execute("setvar MBBSCONFIGDIR %s" % mbbsuserdir)
              
          elif platform=="win32":
              
              self.execute("setvar MBBSMAINCONFIGDIR c:\python25\mbbs")
              self.execute("setvar MBBSCONFIGDIR c:\python25\mbbs")
          
          userconfigname = os.path.join(self.execute("getvar MBBSCONFIGDIR"), "mbbsuser.conf")
          
          self.userconfig = mbbs_userconfig(userconfigname)
          self.execute("setvar MBBSEDITOR %s" % self.userconfig.editor)
          
          projdirconfigname = os.path.join(self.execute("getvar MBBSCONFIGDIR"), "projdirs.conf")
          self.projects = mbbs_projdirconfig(projdirconfigname)
          
    def lookupProject(self, name):
      userconfigdir = self.execute("getvar MBBSCONFIGDIR")
      pdcf = os.path.join(userconfigdir, "projectdirs.conf")
      fd = open(pdcf)
      fd.close()
          
    def mbbs_run(self,param=""):
      cmd, param=self.divideCmdString(param)
      fd = open(cmd)
      buffer = fd.readlines()
      fd.close()
      for line in buffer:
        self.execute(line)
        
    def mbbs_svn(self, param=""):
      cmd, param2=self.divideCmdString(param)
      if cmd.upper()=="TAG":
          return("tagging")
      
      elif cmd.upper()=="BRANCH":
          return("branching")
      
      elif cmd.upper()=="COMMIT":
          mcmdstr = "svn commit -m \"%s\"" % param2
          print mcmdstr
          os.system(mcmdstr)
          
          
      else:
          os.system("svn %s" % param)
          return("")
    
      
    def replaceVars(self, mstr):
      regexp = re.compile(r"""(%{)([^}]*)(})""")
      res = regexp.findall(mstr)
      for i in res:
          try:
              replstr = self.vars[i[1]]
          except:
              try:
                  replstr = os.environ[i[1]]
              except:
                  replstr = ""
          
          srchstr = "%%{%s}" % i[1]
          mstr = mstr.replace(srchstr, replstr)
      
      return(mstr)
          
    def mbbs_set(self, param=""):
      cmd, param=self.divideCmdString(param)
      
      if cmd.upper()=="PROJECT":
          self.execute("setvar MBBSPROJECTNAME %s" % param)
      
      if cmd.upper()=="VERSION":
          self.execute("setvar MBBSPROJECTVERSION %s" % param)
      
      else:
          return("")
          
    def mbbs_list(self, param=""):
          cmd, param=self.divideCmdString(param)
          if cmd.upper()=="VERSIONS":
              prjdir = self.execute("getvar MBBSPROJECTDIR")
              trunkdir = os.path.join(prjdir, "trunk")
              fd = open(os.path.join(trunkdir, "VERSION"), "r")
              buffer = fd.readlines()
              fd.close()
              trunkversion = buffer[0].split()[0]
              ret = []
              ret.append("%s (trunk)" % trunkversion)
              return(ret)
          
          if cmd.upper()=="PROJECTS":
              ret = []
              for i in self.projects.projects.keys():
                ret.append([self.projects.projects[i].projectname, self.projects.projects[i].projectdir])
              return(ret)
          
    def mbbs_version(self, param=""):
      return("1.99.0-1")
      
    def mbbs_edit(self, param=""):
      cmdstr = "%s %s" % ( self.execute("getvar MBBSEDITOR"), param)
      os.system(cmdstr)
      
    def mbbs_mbbsversion(self, param=""):
      cmd, param=self.divideCmdString(param)
      ret =  "Version: %s" % version()
      return(ret)
      
    def mbbs_setvar(self, param=""):
      cmd, param=self.divideCmdString(param)
      self.vars[cmd] = param.strip()
        
    def mbbs_getvar(self, param=""):
      cmd ,param=self.divideCmdString(param)
      try:
        ret = self.vars[cmd]   
      except:
        ret = "ERROR: Variable not found."
      return(ret)
      
    def mbbs_show(self,param=""):
        cmd ,param=self.divideCmdString(param)
        if cmd.upper()=="VARS":
            return(self.vars)
        elif cmd.upper()=="CURRENT":
            cmd2,param=self.divideCmdString(param)
            if cmd2.upper()=="PROJECT":
                return(self.execute("getvar MBBSPROJECTNAME"))
            elif cmd2.upper()=="VERSION":
                return(self.execute("getvar MBBSPROJECTVERSION"))
                
        
    def mbbs_add(self, param=""):
        """
        
        add project <name> <directory>

        Adds a project to the mbbs configuration and specifies 
        its root working directory. 
            
        """
        cmd ,param=self.divideCmdString(param)
        if cmd.upper()=="PROJECT":
            mprjname ,mdir=self.divideCmdString(param)
            prj = mbbs_projdirconfigentry(mprjname)
            if mdir == "":
                mdir = os.getcwd()
            prj.projectdir = mdir
            self.projects.addProject(prj)
      
    def mbbs_help(self, param=""):
        """
        
        help <command>
        
        provides you a list of possible commands or a specific help to a
        command if it is specified as parameter
            
        """
        cmd ,param=self.divideCmdString(param)
        mret = "mbbs provides following commands:\n\n"
        if cmd == "":
            for i in dir(self):
                if i[:5]=="mbbs_":
                    mcmd = i[5:]
                    mret +="%s " % mcmd
            mret+="\n"
        
        else:
            mstr = "mret = self.mbbs_%s.__doc__" % cmd
            exec(mstr)
            if mret == None:
                mret = "No help available"
        return (mret)
